#include "SceneLog.h"
#include "ScenePlay.h"
#include "App.h"
#include "portrayable.h"

SceneLog::SceneLog() : Scene() {
	needReset_ = true;

	logNum_ = App::c_height / LogManager::c_log_height;
	for (unsigned i = 0; i < logNum_; i++) {
		Portrayable* p = new Portrayable();
		p->setDestPosition(0, LogManager::c_log_height * i);
		lstPort_.push_back(p);
	}
}

void SceneLog::initScene() {
	log_ = (LogManager*)(ScenePlay*)App::getScene(App::SCENE_PLAY)->getManager(ScenePlay::MANAGER_LOG);;
}
SceneLog::~SceneLog() {
}

bool SceneLog::eventChecker(SDL_Event *e) {
	switch (e->type) {
	case SDL_KEYDOWN:
	case SDL_KEYUP:
		return inputChecker(e);
		break;
	}
	return false;
};

void SceneLog::run() {
	if (needReset_)
		resetLog();
	for each(auto port in lstPort_) {
		App::inst()->pushToRendererQueue(port, LAYER_LOG);
	}
};


bool SceneLog::inputChecker(SDL_Event *e) {
	if (e->type == SDL_KEYUP) {
		switch (e->key.keysym.sym) {
		case SDLK_ESCAPE:
			App::changeMenu(App::SCENE_PLAY);
			needReset_ = true;
			return true;

		default:
			break;
		}
	}
	else {

	}

	return false;
};

void SceneLog::resetLog() {
	vector<SDL_Texture*> &log_list = log_->getlog_texture();
	int height = 0;
	auto log_in_manager = log_list.rbegin();
	auto log_in_scene = lstPort_.rbegin();

	unsigned size = log_list.size();
	if (size > logNum_)
		size = logNum_;

	for (unsigned i = 0; i < size; i++) {
		SDL_Texture* t = log_list[log_list.size() - size + i];
		Portrayable* p = lstPort_[i];

		Uint32 format;
		int access;
		int w, h;
		SDL_QueryTexture(t, &format, &access, &w, &h);

		int dx, dy, dw, dh;
		p->getDestRect(dx, dy, dw, dh);

		p->setTexture(t);
		p->setSrcPosition(0, 0, w, h);
		p->setDestPosition(dx, dy, w, h);
	}
	/*
	while (node != log_list.rend()) {
		SDL_Texture* t = *node;
		Uint32 format;
		int access;
		int w, h;
		SDL_QueryTexture(t, &format, &access, &w, &h);
		lstPort_.push_back(new Portrayable(t, 0, 0, w, h));

		int lastindex = lstPort_.size() - 1;
		lstPort_.back()->setDestPosition(30, 5 + lastindex * h);
		height += h;
		if (height >= App::c_width)
			break;
		node++;
	}
	*/
	needReset_ = false;
}